<template>
	<view class="tu-box bai left clearfix" style="height:100%;">
			<children-top title="文/图生视频" page="/pages/index/index"></children-top>
		
		<view class="top-content left clearfix">
			<view class="tu-left clearfix left">
				<view class="tim-left-title left clearfix">
					输入生成视频描述
					
					<label style="float:right;margin-right:20px;" title="作品列表" @click="navigatTo('/pages/works/works')">
						<uni-icons type="icon-component-full" size="25" color="#2979ff" custom-prefix="iconfont"></uni-icons>
					</label>
				</view>
				
				<create-textarea :fontTotalNumber="500" @change="getContent"></create-textarea>
			</view>
			
			<view class="tu-right right clearfix relative">
				<view class="tim-right-title left clearfix relative">
					视频素材
					<view class="tim-right-sucai right">
						<label>
							<uni-icons type="icon-wodezuopin" size="20" color="#666" custom-prefix="iconfont"></uni-icons>
						</label>
						<label>
							素材库
						</label>
						
					</view>
				</view>
				<view class="tim-item-box left clearfix">
					
				<view class="tim-type-box left clearfix relative">
					<view class="tim-type-item left" @click="videoType = 1" :style="videoType==1?'background:#fff;border-radius:7px;box-shadow: 0 0 4px 0 rgba(0, 0, 0, .15);color:#333;font-weight:500;':'background:none;border-radius:0;box-shadow: none;'">
						本地上传
					</view>
					
					<view class="tim-type-item left" @click="videoType = 2" :style="videoType==2?'background:#fff;border-radius:7px;box-shadow: 0 0 4px 0 rgba(0, 0, 0, .15);color:#333;font-weight:500;':'background:none;border-radius:0;box-shadow: none'">
						AI智能生成
					</view>
					
				</view>
				
				<!--本地素材上传图片-->
				<view class="tim-local-box left clearfix">
					<!--上传-->
					
					<view class="tim-local-upload left clearfix" style="margin:7px;"  v-if="file && file[0]" v-for="(item,index) in file">
						<image :src="item.poster" mode="aspectFit" style="width:90px;height:90px;margin-top:5px;margin-left:5px;"></image>
					</view>
					
					
					<view class="tim-local-upload left clearfix" style="margin:7px;">
						<view class="tu-upload-icon left clearfix" style="cursor:pointer;" @click="alertSucai()">
							<view class="tu-upload-icons left" style="margin-top:10px;">
								<uni-icons type="plusempty" size="30" color="#ddd"></uni-icons>
							</view>
							<view class="tu-upload-text left">
								选择图片/视频
							</view>
						</view>
					</view>
					
					
					
					
				</view>
				
				<!--标题开始-->
				<view class="tim-titles left clearfix">
					<view class="tim-title-box left">
						展示标题
					</view>
					<view class="tim-title-input left">
						<input placeholder="请输入标题，在「竖版」中自动展示" />
					</view>
				</view>
				<!--标题结束-->
				
				<!--视频模版开始-->
				<!-- <view class="tim-titles left clearfix" style="height:150px;">
					<video-template></video-template>
				</view> -->
				<!--视频模版结束-->
				
				<!--配音开始-->
				<view class="tim-titles left clearfix" style="height:150px;">
					<view class="tim-title-box left">
						配音
					</view>
					<view class="tim-title-input left">
						<baidu-timbre @confirm="selectedTimbre"></baidu-timbre>
					</view>
				</view>
				<!--配音结束-->
				
				<!--背景音乐开始-->
				<view class="tim-titles left clearfix">
					<background-music :userinfo="userinfo" @selected="setBackgroundMusic"></background-music>
				</view>
				<!--背景音乐结束-->
				
				
				<!--文生视频开始-->
				<view class="wen-video-box left clearfix">
					<!--尺寸列表-->
					<my-size title="视频尺寸" :data="sizeData" @selected="setSizeItem"></my-size>
				</view>
				
				
				
				<view class="tim-submit left clearfix absolute" @click="createVideo()">
					生成视频
				</view>
				
				</view>
			</view>
		</view>
		<!--选择和上传素材弹窗-->
		<zmt-material :file="file" @selectedFile="selectedFile" :userinfo="userinfo" @close="showMaterial=false" :show = "showMaterial"></zmt-material>
		<up-modal :show="showTools" @confirm="showTools = false" content='开启后会对输入的内容进行智能改写。对于较短的内容生成效果提升明显，但会增加耗时。'></up-modal>
		<zmt-modal title="提交中" :show="modalShow" @close="modalShow = false" content="任务提交中···"></zmt-modal>
	</view>
</template>

<style scoped>
	.tim-title-input input{font-size:14px;color:#666;border:1px solid #eee;border-radius: 5px;height:40px;width:calc(100% - 5px);padding-left:5px;background:#f8f8f8;}
	.tim-title-input{width:calc(100% - 40px);margin-left:20px;margin-top:10px;}
	.tim-title-box{width:calc(100% - 40px);margin-left:20px;line-height:40px;height:40px;font-size:.9rem;color:#333;}
	.tim-titles{width:100%;}
	.tim-item-box{width:100%;height:calc(100% - 150px);overflow: auto;margin-top:10px;}
	.tim-local-upload{width:100px;height:100px;margin:20px;border:1px solid #eee;background:#f8f8f8;border-radius: 5px;}
	.tim-local-box{width:calc(100% - 40px);margin-left:20px;margin-top:20px;min-height:150px;max-height:300px;overflow: auto;}
	.tu-upload-image-view image{border-radius: 12px;}
	.tu-image-close{width:30px;height:30px;border-radius: 50%;background:rgba(0,0,0,.7);line-height:30px;text-align: center;top:-5px;right:-5px;cursor:pointer;}
	.tu-upload-image-view{width:100%;height:100%;border-radius: 12px;}
	.tim-submit{width:80%;margin-left:10%;line-height:40px;background-image: linear-gradient(90deg, #4287fe, #298bfe 25%, #0f8ffd 51%, #25b4c1);color:#fff;text-align: center;border-radius: 10px;bottom:30px;left:0;right:0;cursor:pointer;}
	.tu-kuoxie label:last-child{float:right;margin-left:20px;line-height:30px;height:30px;margin-top:-2px;}
	.tu-kuoxie label:first-child{float:left;font-size:14px;color:#333;line-height:30px;}
	.tu-kuoxie{width:calc(100% - 40px);margin-left:25px;height:30px;margin-top:30px;}
	.wen-video-box{margin-top:30px;width:calc(100% - 20px);margin-left:10px;}
	.tu-upload-items{width:130px;height:130px;border-radius: 12px;background:#f7f8fc;margin-left:5px;margin-right:5px;}
	.tu-upload-images{width:100%;height:140px;margin-top:30px;}
	.tu-upload2-img{width:50%;height:100px;margin-top:calc((100% - 100px)/2 + 10px);}
	.tu-upload-img2-box{width:100%;height:100%;}
	.tu-upload-icons,.tu-upload-text{width:100%;line-height:30px;text-align: center;color:#999;font-size:13px;}
	.tu-upload-icon{width:200px;height:100px;margin-left:calc((100% - 200px)/2);margin-top:calc((100% - 100px)/2 + 10px);}
	.tu-upload-image{width:140px;height:140px;background:#f7f8fc;border-radius: 12px;margin-top:30px;margin-left:calc((100% - 140px)/2);}
	.tim-right-sucai label:first-child{border-right:1px solid #f8f8f8;}
	.tim-right-sucai label{font-size:12px;line-height:30px;float:left;width:49.5%;text-align: center;}
	.tu-upload-box{width:280px;margin-left:20px;margin-top:20px;height:250px;}
	.tim-type-item{width:calc(50% - 5px);height:35px;line-height:35px;margin:5px;margin-top:2.5px;margin-left:2.5px;margin-right:2.5px;cursor: pointer;position: relative;text-align: center;transition: color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);font-size:13px;color:#666;}
	.tim-type-box{width:calc(100% - 40px);margin-left:20px;background-color: rgba(0, 0, 0, 0.04);height:40px;margin-top:40px;border-radius: 7px;}
	.tim-right-sucai{margin-right:10px;height:30px;border:1px solid #eee;width:100px;border-radius: 15px;margin-top:-8px;overflow: hidden;}
	.tim-right-title{width:calc(100% - 20px);padding-left:20px;margin-top:20px;font-size:14px;color:#666;}
	.tim-left-title{width:calc(100% - 20px);padding-left:20px;lcolor: rgb(21, 27, 38);font-size: 18px;font-weight: 500;line-height: 28px;margin-top:20px;}
	.tim-left{width:70%;height:100%;background:#fff;border-radius: 15px;}
	.tu-left{width:calc(100% - 420px);height:100%;background:#fff;border-radius: 15px;}
	.top-content{width: 96%;height: calc(100% - 110px);margin-left: 2%;margin-top: 70px;}
	body, uni-page-body{height:100%;}
	.tu-right{width:400px;height:100%;background:#fff;border-radius: 15px;}
</style>

<script>
	var global =uniCloud.importObject('global',{customUI:true});
	var aliyun =uniCloud.importObject('aliyun',{customUI:true});
	var baidu =uniCloud.importObject('baidu',{customUI:true});
	var db = uniCloud.database();
	import common from '@/static/js/common.js';
	export default {
		data() {
			return {
				access_token:null,//百度accesstoken
				backgroundMusic:null,//背景音乐
				file:[],//选择好素材以后
				showMaterial:false,//弹出素材弹窗
				userinfo:{},//登录用户信息
				modalShow:false,
				content:'',//文本内容
				image:[],//上传之后的图片
				currentUploadItem:null,
				percent:0,
				promptExtend:true,//智能扩写
				showTools:false,
				videoType:1,//文生还是图生，1：文生，2：图生
				imgNumber:1,//单图还是双图，1：单图，2：双图
				size:'720*1280',
				proportion:[1080,1920],//比例
				modelItem:'wanx2.1-t2v-turbo',
				timbre:{},//选中后的音色
				model:[
					{
						text:'标准',
						value:'wanx2.1-t2v-turbo'
					},
					{
						text:'高品质',
						value:'wanx2.1-t2v-plus'
					}
				],
				sizeData:[
					{
						text:'竖屏',
						value:'1080*1920',
						icon:'icon-rectangle1',
						size:15
					},
					{
						text:'横屏',
						value:'1920*1080',
						icon:'icon-16gl-rectangle',
						size:15
					}
				],
			}
		},
		created() {
			var that = this;
			//获取百度token
			that.getAccessToken();
			uni.getStorage({
				key:'login-userinfo',
				success:function(res){
					var userinfo = res.data;
					if(!userinfo || !userinfo._id){
						uni.navigateTo({
							url: '/pages/index/index'
						});
					}else{
						that.userinfo = userinfo;
					}
				},
				fail() {
					uni.navigateTo({
						url: '/pages/index/index'
					});
				}
			});
		},
		methods: {
			//获取token
			getAccessToken(){
				baidu.getAccessToken().then(res=>{
					this.access_token = res.result.access_token;
				});
			},
			//设置背景音乐
			setBackgroundMusic(e){
				this.backgroundMusic = e.url;
			},
			//获取和更新视频时长
			getDuration(id,url){
				var audio =  uni.createInnerAudioContext();
				audio.src = url;
				audio.onCanplay(()=>{
					var duration = parseInt(audio.duration);
					db.collection('music').where({_id:id}).update({
						duration:duration
					})
				})
			},
			//选择音色以后
			selectedTimbre(e){
				this.timbre = e;
			},
			//确定选择素材以后
			selectedFile(e){
				this.file = e;
			},
			//弹出素材弹窗
			alertSucai(){
				this.showMaterial = true;
			},
			//创建视频
			createVideo(){
				var that = this;
				var content = that.content;
				var file = that.file;
				var timbre = that.timbre;
				var proportion = that.proportion;
				
				if(file.length < 1){
					uni.showToast({
						title:'请至少上传一张图片和输入20字以上的内容',
						icon:'none',
						duration:2000
					})
					
					return false;
				}
				
				var structs = [
					{
						"text": content,
						"type": "text"
					}
				]
				for(var i = 0;i < file.length;i++){
					structs.push({
						type:'image',
						 "mediaSource": {
						    "type": 3,
						    "url": file[i].url
						}
					});
				}
				var data ={
					"source": {
						"structs": structs
					},
					"config": {
						"resolution": proportion,
						"productType": "video",
						"ttsPer":timbre.voice,
						//"templateId": "48"
						"bgMusic":{
							"mediaSource":{
								type:3,
								url:this.backgroundMusic
							}
						},
						"caption":{
							fontColor:'333333',
							fontAlpha:70,
							bgColor:'ffffff',
							bgAlpha:70
						}
					}
				}
				
				
				var resolution = data.config.resolution;
				var size = resolution[0]+'*'+resolution[1];
				var proportion = common.calculateRatio(size);
				baidu.getVideoTaskId(this.access_token,data).then(res=>{
					console.log('jobsss',res);
					var status = res.result.status;
					console.log('statussss',status);
					if(status == 200 && !res.result.data.error_code){
						var jobId= res.result.data.data.id;
						var addData = {
							"app_title": "一键成片",
							"app_id": "67cf8ea77c8de46baf8b05e4",
							"uid": this.userinfo._id,
							"content":content,
							"task_id": jobId.toString(),
							"size": resolution[0]+'*'+resolution[1],
							"proportion": proportion,
							"type": "baidu-video",
							"task_status": "0",
							"task_status_text": "排队中"
						}
						
						db.collection('create_result').add(addData).then(res=>{
							uni.redirectTo({
								url: '/pages/works/works'
							});
						});
					}else{
						uni.showToast({
							title:'内容不能少于20个字符且必须包含一张图片或一个视频',
							icon:'none',
							duration:4000
						})
					}
					
				});
			},
			
			//设置品质
			setModel(e){
				this.modelItem = e.value;
			},
			//获取编辑器内容
			getContent(e){
				this.content = e;
			},
			//选择尺寸以后
			setSizeItem(item){
				var proportion = item.value.split("*");
				this.proportion = proportion;
				this.size = item.value;
			},
			//删除图片
			removeImage(item){
				var that = this;
				var image = that.image;
					uni.showLoading({
						title:'删除中'
					})
				
				if(image && image[item]){
					//删除图片
					var imgPath = image[item].url;
					global.removeFileByPath(imgPath).then(res => {
						uni.hideLoading()
						delete that.image[item];
						that.percent = 0;
							uni.showToast({
								title:'删除成功',
								icon:'none'
							})
						  
					  });
					  
					  
				}
				
			},
			//选择图片
			chooseImage(item){
				var that = this;
				that.currentUploadItem = item;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function (res) {
						var tempFilePaths = res.tempFilePaths[0];
						var size = res.tempFiles[0].size;
						var name = res.tempFiles[0].name;
						var fileName = that.generateUUIDWithExtension(name);//uuid文件名
						//获取图片信息
						uni.getImageInfo({
							src:tempFilePaths,
							success(image) {
								that.uploadImage(tempFilePaths,fileName,image,item);
							}
						});
					}
				});
			},
			//上传图片
			uploadImage(tempFilePaths,fileName,image,item){
				var that = this;
				uniCloud.uploadFile({
				        filePath: tempFilePaths,
				        cloudPath: fileName,
				        onUploadProgress: function(progressEvent) {
				          console.log(progressEvent);
				          var percentCompleted = Math.round(
				            (progressEvent.loaded * 100) / progressEvent.total
				          );
						  
						  that.percent = parseInt(percentCompleted);
				        },
				        success(res) {
							var filePath = res.fileID;
							image.url = filePath;
							that.image[item] = image;
							
							
						}
						
				      });
			},
			//uuid
			 generateUUIDWithExtension(fileName) {
			    // 从文件名中提取扩展名
			    const lastDotIndex = fileName.lastIndexOf('.');
			    let extension = '';
			    if (lastDotIndex!== -1) {
			        extension = fileName.slice(lastDotIndex);
			    }
			    // 生成 UUID
			    const uuid = crypto.randomUUID();
			    // 拼接 UUID 和扩展名
			    return uuid + extension;
			}
		}
	}
</script>

